package utils;

import dao.entities.control.User;
import dao.interfaces.IDAOFacade;

public class LoginUtils {

	private static String getUserProfile(String userName, String password)
			throws Exception {

		// convertim el password a MD5 per comparar amb el almacenat a la BD
		String pwdMD5 = EncryptionUtils.ConvertToMD5(password);

		// busquem el usuari a la BD
		IDAOFacade em = DBUtils.getEntManager();
		User user = (User) em.findObjectByDescription(User.class, userName);

		if (user == null) {
			throw new Exception("invalid_user");
		} else if (!user.getPassword().equals(pwdMD5)) {
			throw new Exception("invalid_password");
		} else {
			return user.getProfile().toString();
		}

	}

	public static String validarUserNamePassword(String userName,
			String password) throws Exception {

		if (userName == null) {
			throw new Exception("invalid_user_format");
		} else if (userName.trim().length() < 4) {
			throw new Exception("invalid_user_format");
		} else if (password == null) {
			throw new Exception("invalid_password_format");
		} else if (password.trim().length() < 8) {
			throw new Exception("invalid_password_format");
		} else if (!password.matches(".*\\d.*")) {
			throw new Exception("invalid_password_format");
		} else {
			return getUserProfile(userName, password);
		}

	}

}
